package com.sp.fresh_produce.web;

import com.sp.fresh_produce.model.pojo.User;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;

/**
 * 角色上下文过滤器
 * <p>
 * 将当前用户与是否管理员的信息注入请求属性，便于后续处理链使用。
 */
@Component
public class RoleContextFilter implements Filter {

    public static final String ATTR_CURRENT_USER = "currentUser";
    public static final String ATTR_IS_ADMIN = "isAdmin";
    private static final String USER_SESSION_KEY = "user";

    @Autowired
    private RememberMeService rememberMeService;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpReq = (HttpServletRequest) request;
        String path = httpReq.getRequestURI();
        if (path.startsWith("/v3/api-docs") || path.startsWith("/swagger-ui") || path.startsWith("/webjars") || path.equals("/swagger-ui.html")) {
            chain.doFilter(request, response);
            return;
        }
        HttpSession session = httpReq.getSession();
        User user = (User) session.getAttribute(USER_SESSION_KEY);
        if (user == null) {
            // 尝试从记住我 Cookie 自动登录
            User auto = rememberMeService.autoLogin(httpReq);
            if (auto != null) {
                session.setAttribute(USER_SESSION_KEY, auto);
                user = auto;
            }
        }
        request.setAttribute(ATTR_CURRENT_USER, user);
        request.setAttribute(ATTR_IS_ADMIN, user != null && user.getRole() != null && user.getRole() == 2);
        chain.doFilter(request, response);
    }
}


